package services

import (
	. "ircove.com/common"
	. "ircove.com/irc"
	 "strings"
)

type clientx struct {
	clients map[string] uint64
}

var channels = make(map[string]*clientx, 40)
func PushMessage(context *VFContext) *VFResult {

	if context.Client.Session == nil || !context.Client.Session.UserIsAuth {
		return NewVFResult_VFcode(SesstionInvaild)
	}
	device_token := context.Args["device_tokens"]
	if len(device_token) == 0 {
		return NewVFResult_VFcode(ErrorArgument.Clone("device_tokens is null"))
	}
	c := context.Client.Server.Clients[device_token]
	if c != nil {
		x := XMessage_MapFrom(context.Args)
		r := NewVFResult(x)
		m := VFResult_ToMessage(context.Request, r)
		c.SendMessage(m)
	}
	return nil
}
func PushChannelMessage(context *VFContext) *VFResult {

	if context.Client.Session == nil  {
		return NewVFResult_VFcode(SesstionInvaild)
	}
	channel := context.Args["channel"]
	if len(channel) == 0 {
		return NewVFResult_VFcode(ErrorArgument.Clone("channel is null"))
	}
	clientx:= channels[channel]
	if clientx !=nil && len(clientx.clients)>0 {

		x := XMessage_MapFrom(context.Args)
		r := NewVFResult(x)
		message := VFResult_ToMessage(context.Request, r)

		for device_token,id:= range clientx.clients {

            c:=  context.Client.Server.Clients[device_token]
			if c !=nil && id!=context.Client.Id {
				c.SendMessage(message)
			}else {
				delete(clientx.clients,device_token)
			}
		}
	}
	return NewVFResult("ok")
}
func Subscribe(context *VFContext) *VFResult {
	if !context.Client.IsConAuth() {
		return NewVFResult_VFcode(SesstionInvaild.Clone("client is not auth!"))
	}
	channel := context.Args["channel"]
	if len(channel) == 0 {
		return NewVFResult_VFcode(ErrorArgument.Clone("channel is null"))
	}
	strs := strings.Split(channel, "|")
	for _, v := range strs {
		if channels[v] == nil {
			x := new(clientx)
			x.clients = make(map[string]uint64, 1024)
			channels[v] = x
		}
		channels[v].clients[context.Client.DeviceToken] = context.Client.Id
	}
	return NewVFResult("ok")
}
